package best.driver.android.Activity.Register;


import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import best.driver.android.Activity.Base.BaseActivity;
import best.driver.android.AppConstant;
import best.driver.android.AppInfo;
import best.driver.android.Beans.CarItemInfo;
import best.driver.android.Beans.CheckStatus;
import best.driver.android.Beans.DriverInfo;
import best.driver.android.Event.CheckStatusEvent;
import best.driver.android.Event.NewOrderAcceptedEvent;
import best.driver.android.Event.SelectCarEvent;
import best.driver.android.R;
import best.driver.android.RequestFactory;
import best.driver.android.Utils.IDCard;
import best.driver.android.Utils.ImageLoaderListener;
import best.driver.android.Utils.ImageLoaderUtil;
import best.driver.android.View.CanClearEditText;
import best.driver.android.View.ConfirmDialog;
import best.driver.android.View.ConfirmDialogListener;
import best.driver.android.View.HintDialog;
import best.driver.android.View.photocrop.PhotoBase;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.ApiStringRequest;
import best.driver.android.common.network.BestApiError;
import best.driver.android.common.network.BestError;
import best.driver.android.common.utils.StringUtils;
import best.driver.android.manager.UserInfoManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import de.greenrobot.event.EventBus;

public class CheckActivity extends PhotoBase {

    private SelectCarEvent mCarItemInfo;

    @InjectView(R.id.tv_check_status)
    TextView mTvCheckStatus;

    @InjectView(R.id.iv_car_pic)
    ImageView mImgCar;

    @InjectView(R.id.iv_driving_licence)
    ImageView mImgDrivingLicence;

    @InjectView(R.id.iv_identify_front)
    ImageView mImgIdentifyFront;

    @InjectView(R.id.iv_identify_back)
    ImageView mImgIdentifyBack;

    @InjectView(R.id.iv_on_road_licence)
    ImageView mImgOnRoadLicence;

    @InjectView(R.id.iv_operation)
    ImageView mImgOperation;

    @InjectView(R.id.edt_name)
    CanClearEditText mOwnerName;

    @InjectView(R.id.edt_car_number)
    CanClearEditText mCarNumber;

    @InjectView(R.id.edt_identify)
    CanClearEditText mIdentifyNum;

    @InjectView(R.id.tv_operation_hint)
    TextView mTvOperationHint;

    @InjectView(R.id.tv_operation_desc)
    TextView mTvOperationDesc;

    @InjectView(R.id.tv_identify_front_hint)
    TextView mTvIdentifyFrontHint;

    @InjectView(R.id.tv_identify_front_desc)
    TextView mTvIdentifyFrontDesc;

    @InjectView(R.id.tv_identify_back_hint)
    TextView mTvIdentifyBackHint;

    @InjectView(R.id.tv_identify_back_desc)
    TextView mTvIdentifyBackDesc;

    @InjectView(R.id.tv_on_road_licence_hint)
    TextView mTvOnRoadLicenceHint;

    @InjectView(R.id.tv_on_road_licence_desc)
    TextView mTvOnRoadLicenceDesc;

    @InjectView(R.id.tv_driving_licence_hint)
    TextView mTvDrivingLicenceHint;

    @InjectView(R.id.tv_driving_licence_desc)
    TextView mTvDrivingLicenceDesc;

    @InjectView(R.id.tv_car_pic_hint)
    TextView mTvCarPicHint;

    @InjectView(R.id.tv_car_pic_desc)
    TextView mTvCarPicDesc;

    @InjectView(R.id.tv_car_type)
    TextView mTvCarType;

    @OnClick(R.id.fl_identify_front)
    protected void selectIdentifyFrontPic() {
        gotoSelectPhoto(mImgIdentifyFront, mTvIdentifyFrontHint, mTvIdentifyFrontDesc, AppConstant.PHOTO_CERTIFICATION_FRONT);
    }

    @OnClick(R.id.fl_identify_back)
    protected void selectIdentifyBackPic() {
        gotoSelectPhoto(mImgIdentifyBack, mTvIdentifyBackHint, mTvIdentifyBackDesc, AppConstant.PHOTO_CERTIFICATION_BACK);
    }

    @OnClick(R.id.fl_car_pic)
    protected void selectCarPic() {
        gotoSelectPhoto(mImgCar, mTvCarPicHint, mTvCarPicDesc, 2);
    }

    @OnClick(R.id.fl_driving_lience)
    protected void selectDrivingLicencePic() {
        gotoSelectPhoto(mImgDrivingLicence, mTvDrivingLicenceHint, mTvDrivingLicenceDesc, AppConstant.PHOTO_DRIVER);
    }

    @OnClick(R.id.fl_on_road_licence)
    protected void selectOnRoadLicencePic() {
        gotoSelectPhoto(mImgOnRoadLicence, mTvOnRoadLicenceHint, mTvOnRoadLicenceDesc, AppConstant.PHOTO_ON_ROAD);
    }

    @OnClick(R.id.fl_operation)
    protected void selectOperationPic() {
        gotoSelectPhoto(mImgOperation, mTvOperationHint, mTvOperationDesc, 5);
    }

    @OnClick(R.id.ll_select_car)
    protected void selectCar(){
        Intent intent = new Intent(CheckActivity.this, SelectCarActivity.class);
        startActivityForResult(intent, RESULT_OK);
    }

    @OnClick(R.id.btn_sumbit_to_check)
    protected void submitToCheck() {
        UserInfoManager manager = UserInfoManager.getInstance();
        final String identifyFrontId = manager.getIdentifyFrontId();
        final String identifyBackId = manager.getIdentifyBackId();
        final String carPicId = manager.getCarPicId();
        final String drivingLicencePicId = manager.getDrivingCarPicId();
        final String onRoadPicId = manager.getOnRoadPicId();
        final String operationPicId = manager.getOperationPicId();
        final String ownerName = mOwnerName.getText().toString();
        final String carName = mTvCarType.getText().toString();
        final String carNumber = mCarNumber.getText().toString();
        final String idNum = mIdentifyNum.getText().toString();
        if(TextUtils.isEmpty(ownerName)) {
            AppInfo.showToast(this, "请填写姓名");
            return;
        }

        if(TextUtils.isEmpty(idNum)) {
            AppInfo.showToast(this, "请填写身份证号");
            return;
        } else {
            String error = IDCard.IDCardValidate(idNum);
            if(!TextUtils.isEmpty(error)) {
                AppInfo.showToast(this, "请输入真实的身份证号");
                return;
            }
        }

        if(TextUtils.isEmpty(carName)) {
            AppInfo.showToast(this, "请选择车辆型号");
            return;
        }

        if(TextUtils.isEmpty(carNumber)) {
            AppInfo.showToast(this, "请填写车牌号");
            return;
        }

        if(TextUtils.isEmpty(identifyFrontId)) {
            AppInfo.showToast(this, "请上传身份证正面照片");
            return;
        }

        if(TextUtils.isEmpty(identifyBackId)) {
            AppInfo.showToast(this, "请上传身份证背面照片");
            return;
        }

        if(TextUtils.isEmpty(carPicId)) {
            AppInfo.showToast(this, "请上传车辆照片");
            return;
        }

        if(TextUtils.isEmpty(drivingLicencePicId)) {
            AppInfo.showToast(this, "请上传驾驶证照片");
            return;
        }

        if(TextUtils.isEmpty(onRoadPicId)) {
            AppInfo.showToast(this, "请上传行驶证照片");
            return;
        }

//        if(TextUtils.isEmpty(operationPicId)) {
//            AppInfo.showToast(this, "请上传营运执照照片");
//            return;
//        }
        if(UserInfoManager.getInstance().isCheckSucceed()) {
            final ConfirmDialog dialog = new ConfirmDialog(CheckActivity.this, "提交后等待审核期间，您将无法接单！");
            dialog.setTitle("确认提交审核吗？");
            dialog.setConfirmName("确定");
            dialog.setListener(new ConfirmDialogListener() {
                @Override
                public void onClickConfirm() {
                    dialog.dismiss();
                    ApiStringRequest request = RequestFactory.createSubmitToCheckRequest(UserInfoManager.getInstance().getDriverId(),
                            "1", ownerName, mCarItemInfo.vehicleId, carName, carNumber,
                            idNum, identifyFrontId, identifyBackId, carPicId, drivingLicencePicId, onRoadPicId, operationPicId);
                    request.setListener(new ApiRequest.ApiRequestListener<String>() {
                        @Override
                        public void onRequestSuccess(String response) {
                            AppInfo.showToast(CheckActivity.this, "提交成功，请等待审核");
                            finish();
                        }

                        @Override
                        public void onRequestError(BestError error) {
                            if(error instanceof BestApiError) {
                                AppInfo.showToast(CheckActivity.this, ((BestApiError) error).getErrorMessage());
                            }
                        }
                    });
                    AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);

                }
            });
        } else {
            ApiStringRequest request = RequestFactory.createSubmitToCheckRequest(UserInfoManager.getInstance().getDriverId(),
                    "1", ownerName, mCarItemInfo.vehicleId, carName, carNumber,
                    idNum, identifyFrontId, identifyBackId, carPicId, drivingLicencePicId, onRoadPicId, operationPicId);
            request.setListener(new ApiRequest.ApiRequestListener<String>() {
                @Override
                public void onRequestSuccess(String response) {
                    AppInfo.showToast(CheckActivity.this, "提交成功，请等待审核");
                    finish();
                }

                @Override
                public void onRequestError(BestError error) {
                    if(error instanceof BestApiError) {
                        AppInfo.showToast(CheckActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_check);
        ButterKnife.inject(this, view);
        EventBus.getDefault().register(this);
        mIdentifyNum.setMaxLength(18);
        setLeftIvBak(R.drawable.icon_navibar_back);
        setTopTopic("车辆信息");
        showFromCache();
    }

    private void showFromCache() {
        DriverInfo info = UserInfoManager.getInstance().getDriverInfo();
        if(CheckStatus.AUDIT_SUCCESS.equals(info.auditStatus)) {
            mTvCheckStatus.setText("审核通过");
            mTvCheckStatus.setCompoundDrawables(null, null, null, null);
            mTvCheckStatus.setTextColor(getColor(android.R.color.holo_green_light));
        } else if (CheckStatus.DRAFT.equals(info.auditStatus))  {
            mTvCheckStatus.setText("未审核");
            mTvCheckStatus.setTextColor(getColor(R.color.aaaa));
        } else if (CheckStatus.IN_AUDIT.equals(info.auditStatus)) {
            mTvCheckStatus.setText("审核中");
            mTvCheckStatus.setTextColor(getColor(R.color.aaaa));
        } else if (CheckStatus.AUDIT_FAILURE.equals(info.auditStatus)) {
            mTvCheckStatus.setText("审核未通过");
            mTvCheckStatus.setTextColor(getColor(R.color.best_red));
        }

        if(!TextUtils.isEmpty(info.driverLicensePhoto)) {
            ImageLoaderUtil.showImageTriBitmap(StringUtils.generateFileUrl(info.driverLicensePhoto), mImgDrivingLicence, null, new ImageLoaderListener() {
                @Override
                public void onSuccess() {
                    mTvDrivingLicenceDesc.setVisibility(View.VISIBLE);
                    mTvDrivingLicenceHint.setVisibility(View.GONE);
                    UserInfoManager.getInstance().setAcceptOrderStatus(false);
                    EventBus.getDefault().post(new CheckStatusEvent());
                }

                @Override
                public void onFailed() {

                }
            });
        }

        if(!TextUtils.isEmpty(info.identityFrontPhoto)) {
            ImageLoaderUtil.showImageTriBitmap(StringUtils.generateFileUrl(info.identityFrontPhoto), mImgIdentifyFront, null, new ImageLoaderListener() {
                @Override
                public void onSuccess() {
                    mTvIdentifyFrontDesc.setVisibility(View.VISIBLE);
                    mTvIdentifyFrontHint.setVisibility(View.GONE);
                }

                @Override
                public void onFailed() {

                }
            });
        }

        if(!TextUtils.isEmpty(info.identityBackPhoto)) {
            ImageLoaderUtil.showImageTriBitmap(StringUtils.generateFileUrl(info.identityBackPhoto), mImgIdentifyBack, null, new ImageLoaderListener() {
                @Override
                public void onSuccess() {
                    mTvIdentifyBackDesc.setVisibility(View.VISIBLE);
                    mTvIdentifyBackHint.setVisibility(View.GONE);
                }

                @Override
                public void onFailed() {

                }
            });
        }

        if(!TextUtils.isEmpty(info.truckLicensePhoto)) {
            ImageLoaderUtil.showImageTriBitmap(StringUtils.generateFileUrl(info.truckLicensePhoto), mImgOnRoadLicence, null, new ImageLoaderListener() {
                @Override
                public void onSuccess() {
                    mTvOnRoadLicenceDesc.setVisibility(View.VISIBLE);
                    mTvOnRoadLicenceHint.setVisibility(View.GONE);
                }

                @Override
                public void onFailed() {

                }
            });
        }

        if(!TextUtils.isEmpty(info.truckPhoto)) {
            ImageLoaderUtil.showImageTriBitmap(StringUtils.generateFileUrl(info.truckPhoto), mImgCar, null, new ImageLoaderListener() {
                @Override
                public void onSuccess() {
                    mTvCarPicDesc.setVisibility(View.VISIBLE);
                    mTvCarPicHint.setVisibility(View.GONE);
                }

                @Override
                public void onFailed() {

                }
            });
        }

        if(!TextUtils.isEmpty(info.operationLicensePhoto)) {
            ImageLoaderUtil.showImageTriBitmap(StringUtils.generateFileUrl(info.operationLicensePhoto), mImgOperation, null, new ImageLoaderListener() {
                @Override
                public void onSuccess() {
                    mTvOperationDesc.setVisibility(View.VISIBLE);
                    mTvOperationHint.setVisibility(View.GONE);
                }

                @Override
                public void onFailed() {

                }
            });
        }

        if(!TextUtils.isEmpty(info.truckName) && !TextUtils.isEmpty(info.vehicleId)) {
            mTvCarType.setText(info.truckName);
            mCarItemInfo = new SelectCarEvent();
            mCarItemInfo.truckName = info.name;
            mCarItemInfo.vehicleId = info.vehicleId;
        }

        if(!TextUtils.isEmpty(info.identityCardId)) {
            mIdentifyNum.setText(info.identityCardId);
        }

        if(!TextUtils.isEmpty(info.name)) {
            mOwnerName.setText(info.name);
        }

        if(!TextUtils.isEmpty(info.truckNum)) {
            mCarNumber.setText(info.truckNum);
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(SelectCarEvent event) {
        if(event != null) {
            mTvCarType.setText(event.truckName);
            mCarItemInfo = event;
        }
    }


}
